﻿/*
 * TV Torrent Linker by mrmt32 (mrmt32@ph-mb.com)
 * 
 *  This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Net;
using System.Reflection;

namespace TVTorrentLinker
{
    class Program
    {
        [DllImport("kernel32.dll", SetLastError=true)]
        static extern bool CreateSymbolicLink(string lpSymlinkFileName, string lpTargetFileName, int dwFlags);

        [DllImport("Kernel32.dll", CharSet = CharSet.Unicode)]
        static extern bool CreateHardLink(
        string lpFileName,
        string lpExistingFileName,
        IntPtr lpSecurityAttributes
        );

        static int SYMLINK_FLAG_DIRECTORY = 1;

        static void Main(string[] args)
        {

            using (new RedirectIO.OutToFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "linker_log.txt")))
            {
                try
                {
                    if (args.Count() < 10)
                    {
                        Console.WriteLine("Error: invalid arguments");
                        return;
                    }
                    else
                    {
                        string downloadName = args[0];
                        string downloadDirectory = args[1];
                        string downloadTitle = args[2];
                        string downloadPreviousState = args[3];
                        string downloadLabel = args[4];
                        string downloadTracker = args[5];
                        string downloadStatus = args[6];
                        string downloadHash = args[7];
                        string downloadState = args[8];
                        bool isSingle = (args[9] == "single" ||
                                args[9].ToUpper().TrimEnd('\\', '/') == downloadDirectory.ToUpper().TrimEnd('\\', '/'));

                        string targetDir = args[10];
                        string[] tracker = args[11].Split('|');
                        string sbUrl = args[12];

                        if (!Directory.Exists(targetDir))
                            Directory.CreateDirectory(targetDir);

                        if (tracker.Any(downloadTracker.Contains))
                        {
                            if (isSingle)
                            {
                                // Just need to make link to file
                                Console.WriteLine("Making link to '{0}' at '{1}' for download '{2}'", Path.Combine(downloadDirectory, downloadName), Path.Combine(targetDir, downloadName), downloadName);


                                if (!CreateHardLink(Path.Combine(targetDir, downloadName), Path.Combine(downloadDirectory, downloadName), IntPtr.Zero))
                                {
                                    Console.WriteLine("Error creating link: {0}", new Win32Exception(Marshal.GetLastWin32Error()));
                                }
                            }
                            else
                            {
                                // Need to make a link to all video files
                                foreach (string fileName in Directory.EnumerateFiles(downloadDirectory))
                                {
                                    if (Path.GetExtension(fileName).ToUpper() == ".MKV" ||
                                        Path.GetExtension(fileName).ToUpper() == ".AVI" ||
                                        Path.GetExtension(fileName).ToUpper() == ".MP4")
                                    {
                                        Console.WriteLine("Making link to '{0}' at '{1}' for download '{2}'", fileName, Path.Combine(targetDir, Path.GetFileName(fileName)), downloadName);

                                        if (!CreateHardLink(Path.Combine(targetDir, Path.GetFileName(fileName)), fileName, IntPtr.Zero))
                                        {
                                            Console.WriteLine("Error creating link: {0}", new Win32Exception(Marshal.GetLastWin32Error()));
                                        }
                                    }
                                }
                            }

                            // Notify SickBeard
							//sbUrl looks like this: http://username:password@localhost:8002 or this: http://localhost:8002
                            Console.WriteLine("Notify SickBeard");

							string url;
							HttpWebRequest request;

							if (sbUrl.Contains("@")) //test on @ for credentials
							{
								string[] sb = sbUrl.Replace("http://", "").Split('@'); //remove http and split
								string sbDomain = sb[1];
								string[] sbCreds = sb[0].Split(':');

								url = string.Format("http://{1}/home/postprocess/processEpisode?dir={0}&quiet=1", Uri.EscapeUriString(targetDir), sbDomain);

                                Console.WriteLine("Request with credentials {0} password {1}", sbCreds[0], sbCreds[1]);

								request = (HttpWebRequest)HttpWebRequest.Create(url);
								request.Credentials = new NetworkCredential(sbCreds[0], sbCreds[1]);
							}
							else
							{
								url = string.Format("http://{1}/home/postprocess/processEpisode?dir={0}&quiet=1", Uri.EscapeUriString(targetDir), sbUrl.Replace("http://", ""));
								request = (HttpWebRequest)HttpWebRequest.Create(url);
							}

							Console.WriteLine("Notifying SickBeard ({0})", url);
                            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                            Stream data = response.GetResponseStream();
                            string html = String.Empty;
                            using (StreamReader sr = new StreamReader(data))
                            {
                                html = sr.ReadToEnd();
                            }

                            Console.WriteLine("SickBeared returned: {0}", html);
                        }
                        else
                        {
                            Console.WriteLine("Tracker '{0}' not for TV, ignoring", downloadTracker);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error during processing: {0}", ex);
                }
            }
        }
    }
}
